import urllib2
from cmrhelper import GbkToUtf8, UtfToGbk

#coding=utf8
class CMangaBase(object):
    "base Class of mangaparse"
    def __init__(self, url, config, log, picqueue, manganame=None):
        "init"
        self.m_url = url
        self.m_manganame = manganame
        self.m_mangaconfig = config
        self.m_mangalog = log
        self.m_picqueue = picqueue
        
        self.m_chaptercnt = 0
        self.m_chapterlist = []
        self.m_namere = None
        
        self.end = False
        
    def Start(self):
        self.IniRe()
        try:
            self.chaptercontent = urllib2.urlopen(self.m_url).read()
        except:
            self.m_mangalog.writeLog('get page content fail','fatal')
            return
        # if m_manganame is None,then parse manganame
        if not self.m_manganame:
            self.ParseName()
        self.GetChapters()
        if self.m_chapterlist:
            for item in self.m_chapterlist:
                self.ParseChapter(item[0], item[1])
                self.m_mangalog.writeLog(item[1] + " parse ok.")
        self.End()
        self.m_mangalog.writeLog('parser finished')

        
    def ParseName(self):
        "get manga name if name is None"
        self.m_mangalog.writeLog('get manga name')
        if self.namere.findall(self.chaptercontent):
            self.m_manganame = GbkToUtf8(self.namere.findall(self.chaptercontent)[0])
            self.m_mangalog.writeLog('get manga name success, manga name [%s]' %\
                                        self.m_manganame)

    def PushPic(self, item):
        "push pics into piclist"
        self.m_picqueue.pushpic(item)
    
    def GetChapters(self):
        "get manga chapters"
        pass
    
    def ParseChapter(self):
        "parse each chapter to generate url of pictures"
        pass

    def End(self):
        self.end = True
